#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 RethinkDB, all rights reserved.

# issue-url: https://github.com/rethinkdb/rethinkdb/issues/3051
# issue-description: python driver on 2.x throws UnicodeEncodeError when error from server includes unicode

from __future__ import print_function

import os, sys, tempfile, traceback

try:
	unicode
	codeMe = lambda inStr: inStr.decode('utf-8')
except NameError:
	codeMe = lambda inStr: inStr

sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir, 'common'))
import driver, utils

logFile = tempfile.NamedTemporaryFile('w+')
server = driver.Process(console_output=logFile.name)

r = utils.import_python_driver()
conn = r.connect(server.host, server.driver_port)

dbName = 'test'
tableName = codeMe('tableWith—Emdash')

if not 'test' in r.db_list().run(conn):
	r.db_create('test').run(conn)

try:
	r.db(dbName).table_create(tableName).run(conn) # should error because of the unicode
except r.ReqlRuntimeError as e:
	try:
		str(e)
	except UnicodeEncodeError:
		traceback.print_exc()
		sys.exit('Error: got a UnicodeEncodeError when printing an error with Unicode characters.')	
	else:
		print('Got expectd exception: %s' % str(e))
		sys.exit()
else:
	sys.exit('Error: should have gotten an error about the unicode table name')
